<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/14
 * Time: 17:10
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use app\common\status\BaseStatus;

class WarehouseStockLog extends BaseModel
{
    protected $pk = 'log_id';

    /**
     * 出库
     * @var int
     */
    const TYPE_OUT = -1;

    /**
     * 入库
     * @var int
     */
    const TYPE_IN = 1;

    /**
     * 占用
     * @var int
     */
    const TYPE_LOCK = 10;

    /**
     * 释放
     * @var int
     */
    const TYPE_UNLOCK = 20;

    public static $TYPES = [
        self::TYPE_OUT => '出库',
        self::TYPE_IN => '入库',
        self::TYPE_LOCK => '占用',
        self::TYPE_UNLOCK => '释放',
    ];

    protected $insert = ['create_by'];

    protected function getTypeAttr($value)
    {
        return isset(self::$TYPES[$value]) ? self::$TYPES[$value] : $value;
    }

    protected function getRefTypeAttr($value)
    {
        return isset(BaseStatus::$REF_TYPE[$value]) ? BaseStatus::$REF_TYPE[$value] : $value;
    }

    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/16
     * @author longli
     */
    public function operate()
    {
        return $this->belongsTo(Admin::class, 'create_by', 'id');
    }

    /**
     * 关联仓库
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/09
     * @author longli
     */
    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class);
    }

    /**
     * 是否存在库存日志
     * @param string $refSn 业务单号
     * @param int $warehouseId 仓库id
     * @param string $sku SKU
     * @param int $qty 操作数量
     * @param string $refIdType 业务主表
     * @return bool
     * @date 2021/01/01
     * @author longli
     */
    public static function hasBySn($refSn, $warehouseId = 0, $sku = '', $qty = 0, $refIdType = '')
    {
        $model = static::where("ref_sn", trim($refSn));
        if(!empty($sku)) $model->where("sku", trim($sku));
        if(!empty($warehouseId)) $model->where("warehouse_id", $warehouseId);
        if(!empty($qty)) $model->where("qty", $qty);
        if(!empty($refIdType)) $model->where("ref_id_type", trim($refIdType));
        return !!$model->count();
    }
}
